package com.sykuku.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sykuku.common.R;
import com.sykuku.controller.expection.BusinessException;
import com.sykuku.pojo.Category;
import com.sykuku.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(defaultValue = "1") Integer page, Integer pageSize) {
        log.info("用户打开分类管理,起始页码 {},每页显示条数{}", page, pageSize);
        //构造分页构造器
        Page<Category> pages = new Page<Category>(page, pageSize);
        //构造查询条件
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<Category>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        Page<Category> categoryPage = categoryService.page(pages,lambdaQueryWrapper);

        return R.success(categoryPage);
    }

    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        log.info("用户添加分类{}", category);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Category::getName, category.getName());
        List<Category> list = categoryService.list(lqw);
        if (list != null&&list.size() > 0 ) {//list值为零
            log.error("阻止用户添加重复分类");
            throw new BusinessException(0, "该分类名称已存在");
        }
        categoryService.save(category);
        return R.success("添加成功");
    }

    @DeleteMapping
    public void deleteById(Long id) {
        log.info("用户根据id删除分类{}", id);
        categoryService.deleteByID(id);
    }

    //回显菜品分类
    @GetMapping("/list")//根据菜品分类类型传回来分类类型的id
    public R<List<Category>> CategoryType(Category category){

        log.info("给用户回显菜品分类{}",category);

       // LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
       // //可以用list接口查询 条件为type和
       // List<Category> categories = categoryService.CategoryType(type);

    //条件构造器
    LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
    //添加条件
    queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
    //添加排序条件
    queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

    List<Category> list = categoryService.list(queryWrapper);
    return R.success(list);

    }

}
